<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<meta charset="UTF-8"/>
<head>
    <meta charset="UTF-8"/>
    <title>Home</title>
    <script th:src="@{sockjs.min.js}"></script>
    <script th:src="@{stomp.min.js}"></script>
    <script th:src="@{jquery-3.2.1.min.js}"></script>
</head>
<body>

<p>
    聊天室
</p>
<form id="jackForm">
    <textarea rows="4" cols="60" name="text"></textarea>
    <input type="submit"/>
</form>

<script th:inline="javascript">
    $("#jackForm").submit(function (e) {
        e.preventDefault();
        var text = $("#jackForm").find('textarea[name="text"]').val();
        sendSpittle(text);
    });

    /**
     * 连接endpoint名称为/endpointChat的endpoint
     * @type {SockJS}
     */
    var sock = new SockJS("/endpointChat");
    var stomp = Stomp.over(sock);
    stomp.connect('guest','guest',function (frame) {
        /**
         * 订阅/user/queue/notifications发送的消息，这里与在控制器的messagingTemplate.convertAndSendToUser
         * 中定义的订阅地址保持一致。这里多了一个/user,并且这个/user是必须的，使用了/user才会发送消息到指定的用户
         */
        stomp.subscribe("/user/queue/notifications",handleNotification)
    });

    function handleNotification(message) {
        $('#output').append("<b>Received: "+message.body+"</b><br/>")
    }

    function sendSpittle(text) {
        stomp.send("/chat",{},text);
    }

    $('#stop').click(function () {
        sock.close();
    });

</script>

<div id="output"></div>
</body>
</html>